#include "core.h"

CSuggestTips::CSuggestTips()
{
	Initialize("");
}

CSuggestTips::~CSuggestTips()
{
}

CSuggestTips* CSuggestTips::getInstance()
{
	static CSuggestTips *p = NULL;
	if(!p)
	{
		p = new CSuggestTips;
	}
	return p;
}

bool CSuggestTips::Initialize(std::string host)
{
	m_strUrl = "http://";
	m_strUrl += host;
	m_strUrl += "/suggest";
	return true;
}

bool CSuggestTips::Destory()
{
	delete this;
	return true;
}

STSuggestResponse* CSuggestTips::suggest(STSuggestRequest *pRequest)
{
	std::string requestUrl = m_strUrl;
	m_mapRequestParameter = mapRequestParameter;
	m_vecRequestParameter = vecRequestParameter;
	addQuerryParameter("index_name", pRequest->index_name, m_mapRequestParameter, m_vecRequestParameter);
	addQuerryParameter("query", pRequest->query, m_mapRequestParameter, m_vecRequestParameter);
	addQuerryParameter("suggest_name", pRequest->suggest_name, m_mapRequestParameter, m_vecRequestParameter);
	addQuerryParameter("hit", pRequest->hit, m_mapRequestParameter, m_vecRequestParameter);

	std::string strtmp = "";
	if (!Request(requestUrl, "GET", GetQuerryParameter(m_mapRequestParameter, m_vecRequestParameter, "GET", strtmp)))
	{
		printf("[%s]:%d\n", __FUNCTION__, __LINE__);
		return NULL;
	}

	parseSuggestResponse();
	return &m_suggestResponse;
}

bool CSuggestTips::parseSuggestResponse()
{
	Json::Reader reader;
	Json::Value result;
	printf("%s\n", g_buf_tmp.data);
	if (reader.parse(g_buf_tmp.data, result))
	{
		m_suggestResponse.request_id = result["request_id"].asString();
		m_suggestResponse.searchtime = result["searchtime"].asDouble();

		uint32_t count = result["suggestions"].size();
		for (uint32_t i = 0; i < count; i++)
		{
			m_suggestResponse.suggestions.push_back(result["suggestions"][i]["suggestion"].asString());
		}
		if (0 == count)
		{
			uint32_t count = result["errors"].size();
			Json::Value errors = result["errors"];
			for (uint32_t i=0; i<count; i++)
			{
				STErrorInfo errorInfo;
				errorInfo.errorCode = errors[i]["code"].asUInt();
				errorInfo.errorMessage = errors[i]["message"].asString();
				m_suggestResponse.errorList.push_back(errorInfo);
			}
		}
	}
	return true;
}